#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "Terminal.hpp"

using namespace std;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}
struct threadData
{
    struct sockaddr_in server;
    int sockfd;
};
void *recv_mesg(void *args)
{
    Terminal();
    threadData *td = static_cast<threadData *>(args);
    char buffer[1024];
    while (true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(td->sockfd, buffer, 1023, 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            cerr << buffer << endl;
        }
    }
}
void *send_mesg(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    socklen_t len = sizeof(td->server);
    string message;
    while (true)
    {
        cout << "Please Enter@ ";
        getline(cin, message);

        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(td->server), len);
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    threadData td;
    bzero(&(td.server), sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }
    pthread_t recv, send;
    pthread_create(&recv, nullptr, recv_mesg, &td);
    pthread_create(&send, nullptr, send_mesg, &td);

    pthread_join(recv, nullptr);
    pthread_join(send, nullptr);
    close(td.sockfd);
    return 0;
}